'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { titleLike, storeId, itemType, status } = query;
  // 找到当前用户
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  // 找到当前用户的店铺
  const store = await ctx.model.Store.findOne({ where: { userId: currentUser.id } });
  if (store && store.userId === currentUser.id) where.storeId = store.id;
  if (titleLike) where.title = { [ctx.model.Op.like]: `%${titleLike}%` };
  if (storeId) where.storeId = storeId;
  if (itemType) where.itemType = itemType;
  if (status) where.status = status;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'order', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Item.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  ctx.validate({
    title: { type: 'string' },
    price: { type: 'int' },
    storeId: { type: 'int', required: false },
    original: { type: 'int', required: false },
    itemType: { type: 'enum', values: [ 'present', 'commodities' ], required: false },
    imageHash: { type: 'string', required: false },
    imageHashes: { type: 'array', itemType: 'string', required: false },
  });
  const { imageHashes, imageHash, title, price, original, itemType, storeId } = ctx.request.body;
  const data = { storeId, title, price, original, itemType, imageHash, imageHashes };
  if (imageHash) await ctx.service.file.record('image', imageHash);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('exports.create = async ctx currentUser', currentUser);
  const { role, id: userId } = currentUser;
  console.log('exports.create = async ctx currentUser userId', userId);
  const store = await ctx.model.Store.findOne({ where: { userId }, raw: true });
  console.log('exports.create = async ctx currentUser store', store);
  if (store && store.userId === currentUser.id) {
    data.storeId = store.id;
    const item = await ctx.model.Item.create(_.pickBy(
      _.pick(
        data,
        [ 'title', 'storeId', 'price', 'original', 'itemType', 'status', 'imageHash' ]
      ),
      value => value !== null
    ));
    if (imageHashes && imageHashes.length > 0) {
      await ctx.service.file.bulkRecord('image', imageHashes);
      await ctx.model.ItemImage.bulkCreate(imageHashes.map(imageHash => ({
        imageHash, itemId: item.id,
      })));
    }
    ctx.body = item;
  } else {
    switch (role) {
      case 'admin': {
        data.status = 'selling';
        const item = await ctx.model.Item.create(_.pickBy(
          _.pick(
            data,
            [ 'title', 'storeId', 'price', 'original', 'itemType', 'status', 'imageHash' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.ItemImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, itemId: item.id,
          })));
        }
        ctx.body = item;
      }
        break;
      case 'facilitator': {
        const data = { storeId, title, price, original, itemType, imageHash, imageHashes };
        console.log('await ctx.model.Store.findOne data', data);
        const item = await ctx.model.Item.create(_.pickBy(
          _.pick(
            data,
            [ 'title', 'storeId', 'price', 'original', 'itemType', 'status', 'imageHash' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.ItemImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, itemId: item.id,
          })));
        }
        ctx.body = item;
      }
        break;
      default:

    }
  }
};

exports.show = async ctx => {
  const options = {
    include: [
      {
        model: ctx.model.ItemImage,
      },
    ],
  };
  const item = await ctx.model.Item.findByPk(ctx.params.id, options);
  if (item) {
    ctx.body = item;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  const item = await ctx.model.Item.findByPk(ctx.params.id);
  if (item) {
    ctx.validate({
      title: { type: 'string', required: false },
      price: { type: 'int', required: false },
      original: { type: 'int', required: false },
      storeId: { type: 'int', required: false },
      time: { type: 'date', required: false },
      imageHash: { type: 'string', required: false },
      imageHashes: { type: 'array', itemType: 'string', required: false },
    });
    const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
    const store = await ctx.model.Store.findOne({ where: { userId: currentUser.id }, raw: true });
    const { imageHashes, imageHash } = ctx.request.body;
    if (imageHash) await ctx.service.file.record('image', imageHash);
    if (imageHashes && imageHashes.length > 0) {
      await ctx.service.file.bulkRecord('image', imageHashes);
      await ctx.model.ItemImage.destroy({ where: { itemId: item.id } });
      await ctx.model.ItemImage.bulkCreate(imageHashes.map(hash => ({
        imageHash: hash, itemId: item.id,
      })));
    }
    if (store && store.userId === currentUser.id) {
      ctx.body = await item.update(_.pickBy(
        _.pick(
          ctx.request.body,
          [ 'title', 'price', 'original', 'storeId', 'status', 'time', 'imageHash' ]
        ),
        value => value !== null
      ));
    }
    if (currentUser.role === 'admin' || currentUser.role === 'facilitator') {
      ctx.body = await item.update(_.pickBy(
        _.pick(
          ctx.request.body,
          [ 'title', 'price', 'original', 'storeId', 'status', 'time', 'imageHash' ]
        ),
        value => value !== null
      ));
    }
  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const item = await ctx.model.Item.findByPk(ctx.params.id);
  if (item) {
    await item.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
